import requests
import urllib
import json
import string
import random
from mysqldb.models import AllinpayWxchatPos

# wxConf = {
#     "appid": "wx959c3e8ff427eaeb",
#     "secret": "b90fe15bdf84d5109c6159840c10c8e9",
#     "host": "https://open.weixin.qq.com",
#     "rect": "http://ppt.3vppt.com/api/wxRect",
#     "scope": "snsapi_userinfo",  # "snsapi_base",#"snsapi_userinfo"
# }

from requests.packages.urllib3.exceptions import InsecureRequestWarning

# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def has_chocode(len=3, level=0):
    """返回随机数"""
    chars = string.digits
    if level > 0:
        chars += string.ascii_letters
    if level > 1:
        chars += string.punctuation
    return "".join(random.choice(chars) for _ in range(len))


class wxChatRequest(requests.Session):
    """微信公众号SDK"""

    host = "https://api.weixin.qq.com"
    notify = "http://ppt.3vppt.com/api/wxRect"
    scope = "snsapi_userinfo"  # "snsapi_base",#"snsapi_userinfo"

    def __init__(self, wxConf=3):
        super().__init__()
        self.CONF = self.hasConf(wxConf)

    def hasConf(self, idx=1):
        """查询配置"""
        try:
            r = AllinpayWxchatPos.objects.get(id=idx)
        except BaseException as err:
            return None
        else:
            return r

    def hasWebToken(self, code):
        """请求网页授权Token"""
        url = "/cgi-bin/token"
        headers = {"Content-Type": "application/json"}
        params = {
            "grant_type": "authorization_code",
            "appid": self.CONF.chat_appid,  # wxConf["appid"],
            "secret": self.CONF.chat_secret,  # wxConf["secret"],
            "code": code,
        }
        token = self.do_get(url, headers=headers, params=params)
        return token

    def hasWxUserinfo(self, openid, token):
        """请求用户信息"""
        url = "/cgi-bin/user/info"
        headers = {"Content-Type": "application/json"}
        params = {
            "access_token": token,
            "openid": openid,
            "lang": self.CONF.chat_secret,  # wxConf["secret"],
            "code": "zh_CN",
        }
        token = self.do_get(url, headers=headers, params=params)
        return token

    def hasToken(self):
        """请求access_token"""
        url = "/cgi-bin/token"
        headers = {"Content-Type": "application/json"}
        params = {
            "grant_type": "client_credential",
            "appid": self.CONF.chat_appid,
            "secret": self.CONF.chat_secret,
        }
        token = self.do_get(url, headers=headers, params=params)
        print(f"wxChat_Token:{token}")
        return token

    def hasQrCode(self, token, scene):
        """请求二维码"""
        url = "/cgi-bin/qrcode/create"
        headers = {"Content-Type": "application/json"}
        params = {"access_token": token}
        data = {
            "expire_seconds": 300,
            "action_name": "QR_SCENE",  # 临时字符串值
            "action_info": {"scene": {"scene_id": scene}},
        }
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, params=params, data=data)
        return res

    def hasMenuList(self):
        """查询公众号菜单"""
        token = self.hasToken()
        url = "/cgi-bin/get_current_selfmenu_info"
        headers = {"Content-Type": "application/json"}
        params = {"access_token": token.get("access_token")}
        res = self.do_get(url, headers=headers, params=params)
        return res

    def setMenuList(self, data):
        """设置公众号菜单"""
        token = self.hasToken()
        url = "/cgi-bin/menu/create"
        headers = {"Content-Type": "application/json;charset=utf-8"}
        params = {"access_token": token.get("access_token")}
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, params=params, data=data)
        return res

    def sendTemplate(self, data):
        """发送模板消息
        data = {
            "touser":"openid",
            "template_id":"模板ID",
            "url":"http://weixin.qq.com/download", # 选填
            "miniprogram":{                        # 选填
                "appid":"xiaochengxuappid12345",
                "pagepath":"index?foo=bar"
            },
           "data":{
                   "keyword1": {"value":"巧克力"},
                   "keyword2": {"value":"39.8元"},
                   "keyword3": {"value":"2014年9月22日"}
           },
           "client_msg_id":"xxxxxxx" # 选填,防止重发
        }
        """
        token = self.hasToken()
        url = "/cgi-bin/message/template/send"
        headers = {"Content-Type": "application/json;charset=utf-8"}
        params = {"access_token": token.get("access_token")}
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, params=params, data=data)
        return res

    def do_get(self, url="", headers=None, params=None, data=None):
        url = self.host + url
        try:
            r = self.get(url, headers=headers, params=params,
                         data=data, verify=False)
            return r.json() if r and r.status_code == 200 else {}
        except BaseException as err:
            return {}

    def do_post(self, url="", headers=None, params=None, data=None, json=None):
        url = self.host + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=False
            )
            return r.json() if r and r.status_code == 200 else {}
        except BaseException as err:
            return {}

    def Template_Recharge(self, touser, args, path=None):
        """充值到账模板消息 请求参数： openid, 数据列表, h5链接"""
        args = [{"value": i} for i in args]
        token = self.hasToken()
        url = "/cgi-bin/message/template/send"
        headers = {"Content-Type": "application/json"}
        params = {"access_token": token.get("access_token")}

        data = {
            "touser": touser,
            # "id":59686,
            # "name":"账户余额充值到账通知",
            # "menu":"生活服务->休闲娱乐",
            # 账户名称{{thing4.DATA}}
            # 到账金额{{amount1.DATA}}
            # 当前余额{{amount2.DATA}}
            # 到账时间{{time3.DATA}}
            "template_id": "PB3NZ79sUR0U7eVEyCWlSUjM8augVgC3CyVWyY7wo5k",
            "data": dict(zip(["thing4", "amount1", "amount2", "time3"], args)),
            "client_msg_id": has_chocode(6, 1),
        }
        if path:
            data["url"] = path
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, params=params, data=data)
        return res

    def Template_Consumer(self, touser, args, path=None):
        """消费成功通知 请求参数： openid, 数据列表, h5链接"""
        args = [{"value": i} for i in args]
        token = self.hasToken()
        url = "/cgi-bin/message/template/send"
        headers = {"Content-Type": "application/json"}
        params = {"access_token": token.get("access_token")}

        data = {
            "touser": touser,
            # "id":51006,
            # "name":"消费成功通知",
            # "menu":"生活服务->休闲娱乐",
            # 顾客卡号:{{character_string7.DATA}} 32位以内数字、字母或符号
            # 消费金额:{{amount1.DATA}}
            # 账户余额:{{amount25.DATA}}
            # 消费时间:{{time3.DATA}}
            "template_id": "GqfdQn57XTy66ji7YZv1aTy0-k_3QVCk6NFn_36DQq4",
            "data": dict(
                zip(["character_string7", "amount1", "amount25", "time3"], args)
            ),
            "client_msg_id": has_chocode(6, 1),
        }
        if path:
            data["url"] = path
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, params=params, data=data)
        return res

    def Template_ServiceAlert(self, touser, args, path=None, kwargs=None):
        """服务订阅通知 请求参数： openid, 数据列表, 小程序字段"""
        # args = dict(zip(["value"] * len(args), args))
        args = [{"value": i} for i in args]
        token = self.hasToken()
        url = "/cgi-bin/message/template/send"
        headers = {"Content-Type": "application/json;charset=utf-8"}
        params = {"access_token": token.get("access_token")}
        data = {
            "touser": touser,
            # "id":44616,
            # "name":"收到服务订单通知",
            # "menu":"旅游服务->景区服务",
            "template_id": "EIxbvjflqisWvK-LrPhdM06_7lJHDrdOZ1c-f9Ybbvs",
            # 订单号 32位以内数字、字母或符号
            # 产品名称 5个以内的汉字
            # 服务状态 5个以内的汉字
            # 通知时间
            "data": dict(
                zip(["character_string2", "phrase10", "phrase9", "time15"], args)
            ),
            "client_msg_id": str(has_chocode(6, 1)),
        }
        if path:
            data["url"] = path
        if kwargs:
            data["miniprogram"] = {
                "appid": kwargs["appid"],
                # "pagepath": f'pages/businessCard/businessCard?userId={kwargs["dictid"]}',
                "pagepath": f'pages/businessCard/isBotMyAddIdPage?userId={kwargs["dictid"]}&share={kwargs["share"]}',
            }

        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        res = self.do_post(url, headers=headers, params=params, data=data)
        return res


def toMppsModelMessage(title):
    """类目模板库, 返回模板参数"""
    if title == "提现申请提交成功通知":
        return {
            "mid": "_2EwhimGYjqrcymfZ1mL2Q8qIQZUS4EJdFG5SU6hCgw",
            "fields": ["thing5", "amount2", "thing3", "time1"],
        }
    elif title == "提现申请审核通过通知":
        return {
            "mid": "qW29XAxPc-rHMEvDRWa3U0ORs_z82PSLP7iz3b4RrTE",
            "fields": ["amount1", "thing2"],
        }
    elif title == "提现成功通知":
        return {
            "mid": "Xtoq99a-ab4-Z10WwEB4jL9P-4JSVGGFVyNmmiPcGXs",
            "fields": ["amount2", "time3"],
        }
    elif title == "比赛结果通知":  # 新公众号-会员
        return {
            "mid": "G-3qXguDvmYTiwd7yetJspn6omH68CUz1uQi7Tj6XCw",
            "fields": ["thing3", "time11", "thing9"],
        }
    elif title == "订单结算成功通知":
        return {
            "mid": "yTZEGTZPqlhxMTQQAN4c05ZPUCkWLiza16luFKqFm_E",
            "fields": ["thing5", "amount3", "time4"],
        }
    elif title == "订单已出图通知":
        return {
            "mid": "0ZcGhsTGQHJRwixqPXtP6u6q5YnnFHmzQsjd-ckgz6Q",
            "fields": ["character_string2", "thing1", "thing6", "time3"],
        }
    elif title == "剪辑工单处理完成通知":
        return {
            "mid": "tS-WQ99LbZ8SzsLb-mddbtrjHYaQVAoPT9k6avttja0",
            "fields": ["phrase2", "phrase3", "phrase5", "time10"],
        }
    elif title == "收到服务订单通知":
        return {
            "mid": "EIxbvjflqisWvK-LrPhdMx-MZHrMGBHxDKRY8lSRd98",
            "fields": ["character_string2", "phrase10", "thing3", "time15"],
        }
    elif title == "消费成功通知":
        return {
            "mid": "GqfdQn57XTy66ji7YZv1aTy0-k_3QVCk6NFn_36DQq4",
            "fields": ["character_string7", "amount1", "amount25", "time3"],
            # "character_string7":32位以内数字、字母或符号
        }
    elif title == "账户余额充值到账通知":
        return {
            "mid": "PB3NZ79sUR0U7eVEyCWlSUjM8augVgC3CyVWyY7wo5k",
            "fields": ["thing4", "amount1", "amount2", "time3"],
            # thing4: 20个以内字符	可汉字、数字、字母或符号组合
        }
    else:
        return None
